<?php

namespace App\Models;

use DateTimeInterface;
use Encore\Admin\Traits\AdminBuilder;
use Encore\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\Model;

/**
 * App\Models\ProductClass
 *
 * @property int $id
 * @property string $title 标题名称
 * @property int $parent_id 父级id
 * @property int $order 所属的级别
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\ProductClass[] $children
 * @property-read int|null $children_count
 * @property-read \App\Models\ProductClass|null $next
 * @property-read \App\Models\ProductClass $parent
 * @property-read \App\Models\ProductClass $upper
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ProductClass newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ProductClass newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ProductClass query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ProductClass whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ProductClass whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ProductClass whereOrder($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ProductClass whereParentId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ProductClass whereTitle($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ProductClass whereUpdatedAt($value)
 * @mixin \Eloquent
 */
class ProductClass extends Model
{
    use ModelTree, AdminBuilder;

    protected $fillable = ['title', 'parent_id', 'order'];

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format($this->dateFormat ?: 'Y-m-d H:i:s');
    }

    /**
     * 上层关系
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public  function  next() {
        return $this->hasOne(ProductClass::class,'parent_id');
    }

    /**
     * 上层关系
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public  function upper() {
        return $this->belongsTo(ProductClass::class,'parent_id');
    }

    /**
     * @param $classId 分类的级别
     */
    public function getClassLevel($classId):int {
        return self::find($classId)->order;
    }
}
